package com.fengjue.common.utils;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.fdfs.ThumbImageConfig;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @version 1.0
 * @classname FDFSUtil
 * @description TODO
 * @date 2021/3/2 21:54
 * @created by MelodyJerry
 */
@Component
public class FDFSUtil {
    @Autowired
    private FastFileStorageClient fastFileStorageClient; //为方便项目开发集成的简单接口(StorageServer接口)

    @Autowired
    private ThumbImageConfig thumbImageConfig; //缩略图

    /**
     * 上传文件
     *
     * @param file 文件对象
     * @return storePath 文件在服务器中的存储路径 group1/M00/00/08/rBEAA2A_Ci2AU9pHAAYlnPgRYiA554.jpg
     * //todo 暂未实现文件分组：aifruit、apple、banana……
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
//        StorePath storePath = fastFileStorageClient.uploadFile("aifruit", //默认都是放在aifruit分组group
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(),
                file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return storePath.getFullPath(); //返回完整的图片存放路径(含group)
    }

    /**
     * 下载文件(文件字节)
     *
     * @param fileUrl 文件服务器存储路径 group1/M00/00/08/rBEAA2A_Ci2AU9pHAAYlnPgRYiA554.jpg
     * @return byte[] 文件字节
     * @throws IOException
     */
    public byte[] downloadFileByByte(String fileUrl) throws IOException {
        String group = fileUrl.substring(0, fileUrl.indexOf("/"));
        String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
        byte[] bytes = fastFileStorageClient.downloadFile(group, path,
                new DownloadByteArray());
        return bytes;
    }
}
